﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FreeTextBoxControls;

using Blog.Net.Business.BusinessObjects;
using Blog.Net.DataAccess.DataControls;

namespace Blog.Net.Web.Blog
{
    public partial class BlogEntry : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["EntryId"] == "-1")
                    blogFormView.ChangeMode(FormViewMode.Insert);
                else if (Request.QueryString["Mode"] == "1")
                    blogFormView.ChangeMode(FormViewMode.Edit);
            }
        }

        protected void save_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                Control container = blogFormView.FindControl("loginView");
                if (container != null)
                    container = container.Controls[0];
                else
                    container = blogFormView;
                BlogEntryBO blogEntry = new BlogEntryBO();
                Label id = (Label)container.FindControl("id");
                TextBox subject = (TextBox)container.FindControl("subject");
                FreeTextBox body = (FreeTextBox)container.FindControl("body");
                TextBox points = (TextBox)container.FindControl("points");
                TextBox votes = (TextBox)container.FindControl("votes");
                HiddenField createDate = (HiddenField)container.FindControl("createDate");

                if (id != null)
                    blogEntry.Id = int.Parse(id.Text);

                blogEntry.Subject = subject.Text;
                blogEntry.Body = body.Text;

                if (points != null)
                    blogEntry.Points = int.Parse(points.Text);

                if (votes != null)
                    blogEntry.Votes = int.Parse(votes.Text);

                if (!string.IsNullOrEmpty(createDate.Value))
                    blogEntry.CreateDate = DateTime.Parse(createDate.Value);
                else
                    blogEntry.CreateDate = DateTime.Now;

                int? entryId = BlogEntryDataControl.Instance.Save(blogEntry);

                blogFormView.ChangeMode(FormViewMode.ReadOnly);
            }
        }

        protected void deleteButton_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(((LinkButton)sender).CommandArgument))
            {
                int id = Int32.Parse(((LinkButton)sender).CommandArgument);
                BlogEntryDataControl.Instance.Delete(BlogEntryDataControl.Instance.GetById(id));
                Response.Redirect("~/Blog/Default.aspx");
            }
        }
    }
}
